package com.example.helloandroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;

public class Tabs extends Activity {
	TextView tvResult;
	EditText edEtb01_lnch;
	EditText edEtb01_dinr;
	//Hashmap for ListView
	 ArrayList<HashMap<String, String>> sgolfList = new  ArrayList<HashMap<String, String>>();	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lunchdinner);
		initializeElements();
		   try{
		       // check if you are connected or not
		       if(isConnected()){
		           tvResult.setText("You are conncted");
		       }
		       else{
		    	   tvResult.setText("You are NOT conncted");
		       }
			   new MyAsyncTask().execute("abcdefghijklmn");
			   
		    }catch(Exception e){
		     Log.e("Error", e.getMessage());
		     Toast.makeText(this, "Error: "+e, Toast.LENGTH_SHORT).show();
		     //tts.speak("Sorry It seems that there is a problem in connection", TextToSpeech.QUEUE_FLUSH, null);
		   }
		   		
	}
	
	 private void initializeElements() {
		  // TODO Auto-generated method stub
			tvResult = (TextView) findViewById(R.id.tvResult);
			edEtb01_lnch = (EditText) findViewById(R.id.edEtb01_lnch);
			edEtb01_dinr = (EditText) findViewById(R.id.edEtb01_dinr);
		 }
	 
	public boolean isConnected(){
	       ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
	           NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
	           if (networkInfo != null && networkInfo.isConnected()) 
	               return true;
	           else
	               return false;   
	   }

	 	
	 private class MyAsyncTask extends AsyncTask<String, Integer, String>{
		  
	 		@Override
	 		protected String doInBackground(String... params) {
	 			// TODO Auto-generated method stub
	 			return postData(params[0]);
	 		}
	  
	 		public String postData(String valueIWantToSend) {
	 			// Create a new HttpClient and Post Header
	 			InputStream inputStream = null;
	 			HttpClient httpclient = new DefaultHttpClient();
	 			HttpEntity httpEntity = null;
	 			HttpResponse httpresponse = null;
	 			String result="";
	 			//HttpPost httppost = new HttpPost("http://192.168.11.3:8080/sgolf/SgolfTestSearchList.do");
	 			HttpPost httppost = new HttpPost("http://192.168.0.19:8080/sgolf/SgolfTestSearchList2.do");
	  
	 			try {
	 				// Add your data
	 				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	     			nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
	 				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	 				
	 				// set delay time
	 				HttpParams params = httpclient.getParams();
	 				HttpConnectionParams.setConnectionTimeout(params, 3000);
	 				HttpConnectionParams.setSoTimeout(params, 3000);
	  
	 				// Execute HTTP Post Request
	 				httpresponse = httpclient.execute(httppost);
	 				
	 				// receive response as inputStream
	 				//inputStream = httpresponse.getEntity().getContent();
	 				
	 				// convert inputstream to string
	 				//if(inputStream != null)
	 				//	result = convertInputStreamToString(inputStream);
	 				//else
	 				//	result = "Did not work";
	 				
		 			httpEntity = httpresponse.getEntity();
		 			result = EntityUtils.toString(httpEntity);
	 			} catch (ClientProtocolException e) {
	 				// TODO Auto-generated catch block
	 			} catch (IOException e) {
	 				// TODO Auto-generated catch block
	 			}
				return result;
	 		}
	 		
	 		@Override
	        protected void onPostExecute(String result) {
	 			//Toast.makeText(getBaseContext(), "REeived!"+result+";;", Toast.LENGTH_LONG).show();
	 			
	 			// parse received data to json
	 		   Log.i("data received from server:",result);
	 		   
	 		   try {
	 			   JSONArray jArr = new JSONArray(result);
	 			   
	 			   
	 			// looping through All Contacts
                for (int i = 0; i < jArr.length(); i++) {
                    JSONObject c = jArr.getJSONObject(i);
                     
                    String etb01_lnch = c.getString("etb01_lnch");
                    String etb01_dinr = c.getString("etb01_dinr");

                    // tmp hashmap for single contact
                    HashMap<String, String> s = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    s.put("etb01_lnch", etb01_lnch);
                    s.put("etb01_dinr", etb01_dinr);

                    // adding contact to contact list
                    sgolfList.add(s);
                }
                HashMap<String, String> takeMap1 = (HashMap<String,String>)sgolfList.get(0);
                edEtb01_lnch.setText(takeMap1.get("etb01_lnch"));
                edEtb01_dinr.setText(takeMap1.get("etb01_dinr"));
                
	 		   } catch (JSONException e) {
	 			  Toast.makeText(getBaseContext(), "JSONException;;"+e.getMessage(), Toast.LENGTH_LONG).show();
 			  e.printStackTrace();
	 		   }
	 			
	            tvResult.setText(result);
	        }
	 		
			// convert inputstream to String
	 	    private String convertInputStreamToString(InputStream inputStream) throws IOException{
	 	        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
	 	        String line = "";
	 	        String result = "";
	 	        while((line = bufferedReader.readLine()) != null)
	 	            result += line;
	 	 
	 	        inputStream.close();
	 	        return result;
	 	 
	 	    }

	 	}


}






	


